package com.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	public static SqlSessionFactory factory;
	public static SqlSession session;
	
	static {
		InputStream input = null;
		try {
			input = Resources.getResourceAsStream("conf.xml");
			factory = new SqlSessionFactoryBuilder().build(input);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 返回接口对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getMapper(Class<?> ob) {
		 session = factory.openSession();
		 return (T) session.getMapper(ob);
	}
	
	/**
	 * 关闭查询session
	 * @param
	 */
	public static void closeSelect() {
		if(session != null) session.close();
	}
	
	/**
	 * 关闭前先执行commit()提交
	 */
	public static void closeCommit() {
		session.commit();
		if(session != null) session.close();
	}
}
